package com.xy6.jvm.fork.test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * 将一个数组中每一个元素的值加1
 * 
 * <pre>
 * 具体实现为：
 * 将大数组不断分解为更短小的子数组，当子数组长度不超过10的时候，对其中所有元素进行加1操作。
 * </pre>
 * 
 * @author frank
 * @since 2018-01-01
 */
public class NumPlusSubTask extends RecursiveAction {

	private static final long serialVersionUID = -7507814727739876342L;

	/**
	 * 集合
	 */
	private int[] a;
	/**
	 * 开始
	 */
	private int beg;
	/**
	 * 结束
	 */
	private int end;

	public NumPlusSubTask(int[] a, int beg, int end) {
		super();
		this.a = a;
		this.beg = beg;
		this.end = end;
	}

	@Override
	protected void compute() {
		if (end - beg > 10) {
			int mid = (beg + end) / 2;
			NumPlusSubTask t1 = new NumPlusSubTask(a, beg, mid);
			NumPlusSubTask t2 = new NumPlusSubTask(a, mid, end);
			invokeAll(t1, t2);
		} else {
			for (int i = beg; i < end; i++) {
				a[i] = a[i] + 1;
			}
		}
	}


	public final static ForkJoinPool mainPool = new ForkJoinPool();
	
	public static void main(String[] args) {
		int n = 26;
		int[] a = new int[n];
		for(int i=0; i<n; i++){
			a[i] = i;
		}
		NumPlusSubTask task = new NumPlusSubTask(a, 0, n);
		mainPool.invoke(task);
		for(int i=0; i<n; i++){
			System.out.println(a[i]);
		}
	}
}
